package com.kbtxwer.tmss;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.kbtxwer.tmss.URLsupport.GetPostUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Article_Detail extends AppCompatActivity {
Toolbar toolbar;
Intent intent;
ListView dList;
JSONObject jo;
JSONArray ja;
List<Map<String,String>> allArticleList;
StringBuffer sb;
String basicURL;
SimpleAdapter adapter;
MyHandler handler;
public static final int GET_ARTICLE_LIST = 0x456;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_detail);
        intent = getIntent();
        basicURL = intent.getStringExtra("basicURL");
        toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle(intent.getStringExtra("title"));
        toolbar.setNavigationOnClickListener(v->{
            finish();
        });
        dList = findViewById(R.id.detailList);
        handler = new MyHandler(new WeakReference<>(this));
        new Thread(()->{
            String str = GetPostUtil.sendGet(basicURL + "json","","GBK");
            Message msg = new Message();
            msg.what = GET_ARTICLE_LIST;
            msg.obj = str;
            handler.sendMessage(msg);
        }).start();
    }
    private class MyHandler extends Handler {
        private WeakReference<Article_Detail> articleDetail;
        public MyHandler(WeakReference<Article_Detail> articleDetail){
            this.articleDetail = articleDetail;
        }
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case GET_ARTICLE_LIST:{
                    //在这里完成对文章列表的更新
                    //Toast.makeText(Article_Detail.this,msg.obj.toString(),Toast.LENGTH_LONG).show();
                    try {
                        jo = new JSONObject(msg.obj.toString());
                        ja = jo.getJSONArray("article");
                        allArticleList = new ArrayList<>();
                        //在循环中对String进行大量拼接会浪费很多内存常量池，利用StringBuffer提高性能
                        sb = new StringBuffer();
                        for(int i=0;i<ja.length();i++){
                            jo = ja.getJSONObject(i);
                            Map<String,String> map = new HashMap<>();
                            map.put("aid",String.valueOf(i+1));
                            sb.delete(0,sb.length());
                            sb.append(jo.getString("name"));
                            sb.delete(sb.length()-5,sb.length());
                            //为标题换行
                            if(sb.length()>13) sb.insert(14,'\n');
                            map.put("name",sb.toString());
                            map.put("date",jo.getString("date"));
                            allArticleList.add(map);
                        }
                        //Toast.makeText(Article_Detail.this,"解析到文章总数：" + ja.length(),Toast.LENGTH_SHORT).show();
                        //配置适配器
                        adapter = new SimpleAdapter(Article_Detail.this,allArticleList,R.layout.article_detail_list,
                                new String[]{"aid","name","date"},new int[]{R.id.aid,R.id.title,R.id.update});
                        dList.setAdapter(adapter);
                        //设置单篇文章的点击事件
                        dList.setOnItemClickListener((p,v,pos,index)->{
                            TextView addr = v.findViewById(R.id.title);
                            sb.delete(0,sb.length());
                            sb.append(addr.getText().toString());
                            if(sb.length()>14&&sb.charAt(14)=='\n') sb.delete(14,15);
                            Intent intent = new Intent(Article_Detail.this,ArticleView.class);
                            intent.putExtra("title",sb.toString());
                            intent.putExtra("viewAddress",basicURL + sb.toString() + ".html");
                            startActivity(intent);
                        });
                        dList.setOnItemLongClickListener((p,v,pos,index)->{
                            TextView addr = v.findViewById(R.id.title);
                            sb.delete(0,sb.length());
                            sb.append(addr.getText().toString());
                            if(sb.length()>21&&sb.charAt(21)=='\n') sb.delete(21,22);
                            Toast.makeText(Article_Detail.this,sb.toString(),Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(basicURL + sb.append(".html").toString()));
                            startActivity(intent);
                            return true;
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(Article_Detail.this,"错误：数据无法解析为json格式，请联系我查明原因",Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            }
        }
    }

}
